package com.hzqy.service.weather;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hzqy.commons.utils.PublicUtil;
import com.hzqy.persistence.dao.weather.WeatherForecastDao;
import com.hzqy.web.vo.weather.WeatherForecastVo;

public class WeatherCacheUtil {
	private static final Log LOG = LogFactory.getLog(WeatherCacheUtil.class);
	private static HashMap<String,WeatherForecastVo> weatherHashMap = new HashMap<String,WeatherForecastVo>();
	private static WeatherForecastDao weatherForecastDao;
	private static final String dateTime = PublicUtil.getCurDateTime("YYYY-MM-dd");
	public WeatherCacheUtil(){}
	
	public WeatherCacheUtil(WeatherForecastDao weatherForecastDao){
		this.weatherForecastDao = weatherForecastDao;
	}
	public static WeatherForecastVo getWeatherForecastVo(WeatherForecastVo vo) {
		if(vo.getF_wf_id() > 99){
			weatherHashMap.clear();
			LOG.debug("清空缓存-dateTime:"+dateTime);
		}
		if (weatherHashMap.isEmpty() || weatherHashMap.get(vo.getAreaCodeid() + dateTime) == null) {
			initMap(vo);
		}
		WeatherForecastVo wfvo = new WeatherForecastVo();
		if(!weatherHashMap.isEmpty()){
			wfvo = weatherHashMap.get(vo.getAreaCodeid() + dateTime);
		}
		return wfvo;
	}
	
	private static void initMap(WeatherForecastVo vo) {
		WeatherForecastVo wForecastVo = weatherForecastDao.selectWeatherForecastVo(vo);
		if (wForecastVo != null) {
			String deleteKey = "";
			for(Map.Entry<String, WeatherForecastVo> entry : weatherHashMap.entrySet()){
				String key = entry.getKey();
				if(key.startsWith(vo.getAreaCodeid())){
					deleteKey = key;
					break;
				}
			}
			//weatherHashMap.clear();
			weatherHashMap.remove(deleteKey);
			String date = wForecastVo.getF_wf_date().substring(0,10);
			weatherHashMap.put(vo.getAreaCodeid()+date, wForecastVo);
		}
	}
	
	
	public static void main(String[] args) {
		String date = PublicUtil.getCurDateTime("YYYY-MM-dd");
		System.out.println("date:"+date);
	}
}
